package nc.impl.hrpbm.budgetreply.budgetreply;

import cn.hutool.core.util.ArrayUtil;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.impl.hrppl.pjapplication.pjappl.SJXMUtil;
import nc.impl.pubapp.pattern.data.bill.BillQuery;
import nc.itf.hrpbm.budgetmake.budgetmake.IBudgetMakeVOService;
import nc.itf.hrpbm.fourcgxm.fourcgxm.IFourcgxmVOService;
import nc.itf.hrpbm.sjxm.sjxmh.ISjxmHVOService;
import nc.itf.hrppl.pjapplication.pjappl.IPJApplHVOService;
import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.jdbc.framework.processor.MapProcessor;
import nc.vo.fourcgxm.fourcgxm.AggFourcgxmVO;
import nc.vo.fourcgxm.fourcgxm.FourcgxmVO;
import nc.vo.hrpbm.budgetadjust.AggBudgetAdjustVO;
import nc.vo.hrpbm.budgetadjust.BudgetAdjustDetailVO;
import nc.vo.hrpbm.budgetadjust.BudgetAdjustVO;
import nc.vo.hrpbm.budgetmake.AggBudgetMakeVO;
import nc.vo.hrpbm.budgetmake.BudgetMakeDetailVO;
import nc.vo.hrpbm.budgetmake.BudgetMakeVO;
import nc.vo.hrpbm.budgetreply.AggBudgetReplyVO;
import nc.vo.hrpbm.budgetreply.BudgetReplyDetailVO;
import nc.vo.hrpbm.budgetreply.BudgetReplyVO;
import nc.vo.hrppl.pjapplication.AggPjapplVO;
import nc.vo.hrppl.pjapplication.PJApplHVO;
import nc.vo.hrppl.pjapplication.PjapplPVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.CircularlyAccessibleValueObject;
import nc.vo.pub.ISuperVO;
import nc.vo.pub.VOStatus;
import nc.vo.pub.lang.UFDouble;
import nc.vo.sjxm.sjxm.AggSjxmVO;
import nc.vo.sjxm.sjxm.SjxmBVO;
import nc.vo.sjxm.sjxm.SjxmHVO;
import nccloud.commons.lang.ArrayUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 项目预算批复回写
 */
public class CGFourWriteBakDataUtil {
    private IUAPQueryBS queryBS;
    private BaseDAO baseDAO;
    private ISjxmHVOService sjxmHVOService;
    private IBudgetMakeVOService  budgetMakeVOService;
    private IPJApplHVOService pjApplHVOService;
    BillQuery<AggBudgetReplyVO> queryPF = new BillQuery<AggBudgetReplyVO>(AggBudgetReplyVO.class);
    BillQuery<AggBudgetMakeVO> queryBZ = new BillQuery<AggBudgetMakeVO>(AggBudgetMakeVO.class);
    BillQuery<AggPjapplVO> querySQD = new BillQuery<AggPjapplVO>(AggPjapplVO.class);
    BillQuery<AggSjxmVO> queryCG = new BillQuery<AggSjxmVO>(AggSjxmVO.class);
    BillQuery<AggBudgetAdjustVO> queryTZ = new BillQuery<AggBudgetAdjustVO>(AggBudgetAdjustVO.class);

    /**
     * 项目预算编制审批
     * @param vos
     * @throws BusinessException
     */
    public static void callbackApproveBudgetMakeAggVOs(AggBudgetMakeVO... vos) throws BusinessException {
        if (ArrayUtils.isEmpty(vos)) {
            return;
        }
        CGFourWriteBakDataUtil util = new CGFourWriteBakDataUtil();
        for (AggBudgetMakeVO budgetMakeVO : vos) {
            BudgetMakeVO hvo = budgetMakeVO.getParentVO();
            Object nyear = hvo.getAttributeValue("nyear");
            Object taskstage = hvo.getAttributeValue("taskstage");
            Object taskstate = hvo.getAttributeValue("taskstate");
            if("3".equals(taskstage.toString()) && "10".equals(taskstate.toString())) {
                // 预算编制明细
                BudgetMakeDetailVO[] bzvos = (BudgetMakeDetailVO[])budgetMakeVO.getChildren(BudgetMakeDetailVO.class);
                List<String> lists = new ArrayList<>();
                if(!Objects.isNull(bzvos)){
                    for (BudgetMakeDetailVO bzvo : bzvos) {
                        Object pk_project = bzvo.getAttributeValue("pk_project"); // 对应预算申请单
                        if(null !=  pk_project){
                            if(!lists.contains(pk_project.toString())){
                                lists.add(pk_project.toString());
                            }
                            AggPjapplVO[] sqdaggvos = util.querySQD.query(new String[]{pk_project.toString()});
                            if(ArrayUtils.isEmpty(sqdaggvos)){
                                continue;
                            }
                            PjapplPVO[] cgvos = (PjapplPVO[])sqdaggvos[0].getChildren(PjapplPVO.class);
                            if(ArrayUtils.isEmpty(cgvos)){
                                continue;
                            }
                            SJXMUtil.sjxmCommitHandlerAggvo(sqdaggvos,"1","2","I", nyear);
                        }
                    }
                }

            }else if("1".equals(taskstage.toString()) && "3".equals(taskstate.toString())){// 一上审批项目状态 已打包
                // 预算编制明细
                BudgetMakeDetailVO[] bzvos = (BudgetMakeDetailVO[])budgetMakeVO.getChildren(BudgetMakeDetailVO.class);
                List<String> lists = new ArrayList<>();
                if(!Objects.isNull(bzvos)){
                    for (BudgetMakeDetailVO bzvo : bzvos) {
                        Object pk_project = bzvo.getAttributeValue("pk_project"); // 对应预算申请单
                        if(null !=  pk_project){// 判断项目是否存在编报完成的数据
                            if(lists.contains(pk_project.toString())){
                                continue;
                            }else {
                                lists.add(pk_project.toString());
                            }
                            AggPjapplVO[] sqdaggvos = util.querySQD.query(new String[]{pk_project.toString()});
                            if(ArrayUtils.isEmpty(sqdaggvos)){
                                continue;
                            }
                            PjapplPVO[] cgvos = (PjapplPVO[])sqdaggvos[0].getChildren(PjapplPVO.class);
                            if(ArrayUtils.isEmpty(cgvos)){
                                continue;
                            }
                            String bbSql = util.buildQueryBBSQL(pk_project,nyear);
                            List<Map<String,Object>> o = (List<Map<String,Object>>)util.getBaseDAO().executeQuery(bbSql, new MapListProcessor());
                            if (o != null && !o.isEmpty() && o.size() > 0) {
                                SJXMUtil.sjxmCommitHandlerAggvo(sqdaggvos,"1","2","I", nyear);
                                AggPjapplVO[] aggPjapplVOS = util.querySQD.query(new String[]{pk_project.toString()}); // 三级项目申请单
                                util.writeBackAggPjappVO(aggPjapplVOS, nyear);
                            }else {
                                SJXMUtil.sjxmCommitHandlerAggvo(sqdaggvos,"2","2","I", nyear);
                                AggPjapplVO[] aggPjapplVOS = util.querySQD.query(new String[]{pk_project.toString()}); // 三级项目申请单
                                util.writeBackAggPjappVO(aggPjapplVOS, nyear);
                            }
                        }
                    }
                }

            }
        }

    }

    /**
     * 编制回写三级项目申请单
     * @param aggPjapplVOS
     * @param year
     * @throws BusinessException
     */
    protected  void writeBackAggPjappVO(AggPjapplVO[] aggPjapplVOS , Object year) throws BusinessException {
        if(ArrayUtils.isEmpty(aggPjapplVOS)) return;
        CGFourWriteBakDataUtil util = new CGFourWriteBakDataUtil();
        Boolean flag = false;
        for (AggPjapplVO vo : aggPjapplVOS) {
            PJApplHVO hvo = vo.getParentVO();
            String pk_pjappl = hvo.getPk_pjappl();
            PjapplPVO[] cgBVOs = (PjapplPVO[])vo.getChildren(PjapplPVO.class);
            if(ArrayUtils.isEmpty(cgBVOs)) return;
            List<PjapplPVO> lists = new ArrayList<>();
            List<String> contions = new ArrayList<>();
            Boolean isexits = false; // 预算编制提交是否存在采购页签预算年度为空的行
            for (PjapplPVO cgBVO : cgBVOs) {
                Object vbdef2 = cgBVO.getAttributeValue("vbdef2");
                if(vbdef2 == null){
                    isexits =true;
                }
            }
            for (PjapplPVO cgBVO : cgBVOs) {
                Object vbdef1 = cgBVO.getAttributeValue("vbdef1"); // 三级项目中对应的四级项目
                Object vbdef2 = cgBVO.getAttributeValue("vbdef2");// 申请单上的预算年度
                String join = vbdef1+""+year;
                if(isexits){
                    if(vbdef2 != null) continue;
                    cgBVO.setAttributeValue("vbdef2", year);
                    cgBVO.setStatus(VOStatus.UPDATED);
                    contions.add(vbdef1+""+vbdef2);
                    contions.add(vbdef1+""+year);
                    flag = true;
                }else{
                    if(contions.isEmpty() && vbdef2 == null){
                        cgBVO.setAttributeValue("vbdef2", year);
                        cgBVO.setStatus(VOStatus.UPDATED);
                        contions.add(vbdef1+""+vbdef2);
                        contions.add(vbdef1+""+year);
                        flag = true;
                    }else if(contions.contains(join)){
                        continue;
                    } else{
                        PjapplPVO cloneVO = (PjapplPVO)cgBVO.clone();
                        cloneVO.setAttributeValue("vbdef2", year);
                        cloneVO.setAttributeValue("pk_pjappl_p", null);
                        cloneVO.setStatus(VOStatus.NEW);
                        lists.add(cloneVO);
                        contions.add(join);
                        flag = true;
                    }

                }
                lists.add(cgBVO);
            }
            if (!lists.isEmpty()){
                vo.setChildren(PjapplPVO.class, lists.toArray(new PjapplPVO[lists.size()]));
            }
            hvo.setStatus(VOStatus.UPDATED);
        }


        if (flag){
            util.getPjApplHVOService().saveAggPjapplVO(aggPjapplVOS);
        }



    }
    protected String buildAggPjappVOSQL(Object pk_pjappl,Object pk_sjxm , Object year) throws  BusinessException{
        StringBuilder sql = new StringBuilder();
        sql.append("  select \n" );
        sql.append("      h.billno\n" );
        sql.append("  from hrppl_pjappl h\n" );
        sql.append("  inner join hrppl_pjappl_p p on h.pk_pjappl = p.pk_pjappl\n" );
        sql.append("  where h.dr = 0 and p.dr = 0 \n" );
        sql.append("  and p.vbdef2 = '"+year+"' \n" );
        sql.append("  and h.pk_pjappl = '"+pk_pjappl+"' \n" );
        sql.append("  and p.vbdef1 = '"+pk_sjxm+"' ");
        return sql.toString();
    }
    /***
     * 构建预算编报完成的四年级项目查询
     * @param pk_project
     * @return
     * @throws BusinessException
     */
    protected String buildQueryBBSQL(Object pk_project,Object year ) throws BusinessException {
        StringBuilder sql = new StringBuilder();
        sql.append(" select \n" );
        sql.append("    h.taskstate,h.billno\n" );
        sql.append(" from hrpbm_budgetmake h\n" );
        sql.append(" inner join hrpbm_budgetmakedetail b on h.pk_budgetmake = b.pk_budgetmake\n" );
        sql.append(" where h.dr = 0\n" );
        sql.append("   and b.dr = 0\n" );
        sql.append("   and h.nyear = '"+year+"' " );
        sql.append("   and h.taskstate = 99\n" );
        sql.append("   and b.pk_project = '"+pk_project+"' ");
        return  sql.toString();
    }

    /**
     * 项目预算编制取消审批
     * @param vos
     * @throws BusinessException
     */
    public static void callbackUnApproveBudgetMakeAggVOs(AggBudgetMakeVO... vos) throws BusinessException {
        if (ArrayUtils.isEmpty(vos)) {
            return;
        }
        CGFourWriteBakDataUtil util = new CGFourWriteBakDataUtil();
        for (AggBudgetMakeVO budgetMakeVO : vos) {
            BudgetMakeVO hvo = budgetMakeVO.getParentVO();
            Object nyear = hvo.getAttributeValue("nyear");
            Object taskstage = hvo.getAttributeValue("taskstage");
            Object taskstate = hvo.getAttributeValue("taskstate");
            StringBuilder error = new StringBuilder();
            if("9".equals(taskstate.toString()) && "3".equals(taskstage.toString())) {
                // 预算编制明细
                BudgetMakeDetailVO[] bzvos = (BudgetMakeDetailVO[])budgetMakeVO.getChildren(BudgetMakeDetailVO.class);
                List<String> lists = new ArrayList<>();
                if(!ArrayUtils.isEmpty(bzvos)){
                    for (BudgetMakeDetailVO bzvo : bzvos) {
                        Object pk_project = bzvo.getAttributeValue("pk_project"); // 对应预算申请单
                        if(null !=  pk_project){
                            if(!lists.contains(pk_project.toString())){
                                lists.add(pk_project.toString());
                            }
                            AggPjapplVO[] sqdaggvos = util.querySQD.query(new String[]{pk_project.toString()});
                            if(ArrayUtils.isEmpty(sqdaggvos)){
                                continue;
                            }
                            PjapplPVO[] cgvos = (PjapplPVO[])sqdaggvos[0].getChildren(PjapplPVO.class);
                            if(ArrayUtils.isEmpty(cgvos)){
                                continue;
                            }
                            if(!util.checkFourProjectStatusAndISCG(pk_project,nyear, cgvos,error)){
                                SJXMUtil.sjxmCommitHandlerAggvo(sqdaggvos,"3","2","U", nyear);
                            }
                        }
                    }
                }
            } else if ("2".equals(taskstate.toString()) && "1".equals(taskstage.toString())) {
                // 预算编制明细
                BudgetMakeDetailVO[] bzvos = (BudgetMakeDetailVO[])budgetMakeVO.getChildren(BudgetMakeDetailVO.class);
                List<String> lists = new ArrayList<>();
                if(!ArrayUtils.isEmpty(bzvos)){
                    for (BudgetMakeDetailVO bzvo : bzvos) {
                        Object pk_project = bzvo.getAttributeValue("pk_project"); // 对应预算申请单
                        if(null !=  pk_project){
                            if(!lists.contains(pk_project.toString())){
                                lists.add(pk_project.toString());
                            }
                            AggPjapplVO[] sqdaggvos = util.querySQD.query(new String[]{pk_project.toString()});
                            if(ArrayUtils.isEmpty(sqdaggvos)){
                                continue;
                            }
                            PjapplPVO[] cgvos = (PjapplPVO[])sqdaggvos[0].getChildren(PjapplPVO.class);
                            if(ArrayUtils.isEmpty(cgvos)){
                                continue;
                            }
                            Boolean flag = false;
                            for (PjapplPVO cgvo : cgvos) {
                                Object vbdef2 = cgvo.getAttributeValue("vbdef2");
                                if(nyear.equals(vbdef2+"")){
                                    cgvo.setAttributeValue("vbdef2",null);
                                    flag = true;
                                    cgvo.setStatus(VOStatus.UPDATED);
                                }
                            }
                            if(flag){
                                sqdaggvos[0].getParentVO().setStatus(VOStatus.UPDATED);
                                util.getPjApplHVOService().saveAggPjapplVO(sqdaggvos);
                            }
                        }
                    }
                }

            }
            if(error.toString().length() > 0 ){
                throw new BusinessException(error.toString());
            }
        }
    }

    /**
     * 四级项目是否已安排采购
     * @param pk_project
     * @param year
     * @param cgvos
     * @param error
     * @return true :已安排采购、false：未安排采购
     * @throws BusinessException
     */
    protected  Boolean checkFourProjectStatusAndISCG (Object pk_project,Object year,PjapplPVO[] cgvos,StringBuilder error) throws BusinessException {
        for (PjapplPVO cgvo : cgvos) {
            Object vbdef1 = cgvo.getAttributeValue("vbdef1");
            String sql = "SELECT\n" +
                    "\tb.FOURSTATE, h.HOPBILLCODE billcode,h.name billname \n" +
                    "FROM\n" +
                    "\thrpbm_sjxmh h\n" +
                    "\tINNER JOIN hrpbm_sjxmb b ON h.PK_SJXM = b.PK_SJXM \n" +
                    "WHERE\n" +
                    "\th.dr = 0 AND b.dr = 0 and b.FOURSTATE = 3 \n" +
                    "\tand b.YSYEAR = '"+year+"'\n" +
                    "\tand h.PK_SJXM = '"+vbdef1+"'";
            Map<String,Object> obj = (Map<String,Object>)this.getBaseDAO().executeQuery(sql, new MapProcessor());
            if(obj != null && !obj.isEmpty()){
                Object projectName = this.getBaseDAO().executeQuery("select project_name from bd_project where dr = 0 and pk_project = '"+pk_project+"'", new ColumnProcessor());
                error.append("年度:【"+year+"】,三级项目名称:【"+projectName+"】,采购项目信息页签中，四级项目编码:【"+obj.get("billcode")+"】," +
                        "四级项目名称:【"+obj.get("billname")+"】,采购系统已安排采购，不允许收回或取消审批!\n");
            }
        }
        return false;
    }


    /**
     * 项目预算调整提交回写采购系统四级项目
     * @param aggvos
     * @throws BusinessException
     */
    public static void callbackAPPROVEAggBudgetAdjustVO(AggBudgetAdjustVO[] aggvos) throws BusinessException{
        CGFourWriteBakDataUtil util = new CGFourWriteBakDataUtil();
        List<AggFourcgxmVO> listVOs = new ArrayList<>();
        if (aggvos == null || aggvos.length == 0) {
        }else {
            ArrayList<String> pks = new ArrayList<>();
            for (AggBudgetAdjustVO aggvo : aggvos) {
                String pk = aggvo.getParentVO().getPk_budgetadjust();
                pks.add(pk);
            }
            aggvos = util.queryTZ.query(pks.toArray(new String[0]));
            // 获取所有的对应预算编制
            List<String> liskfbzs = new ArrayList<>(); // 所有所提交预算批复中所有的项目
            HashMap<String, Map<String, Object>> pfs = new HashMap<>();// 批复数 二下
            for (AggBudgetAdjustVO aggvo : aggvos) {
                BudgetAdjustVO hvo = aggvo.getParentVO();
                Object pk_budgetadjust = hvo.getAttributeValue("pk_budgetadjust");
                Object pk_budgetmake = hvo.getAttributeValue("pk_budgetmake");
                if(null !=  pk_budgetadjust){
                    liskfbzs.add(pk_budgetmake.toString());
                    BudgetAdjustDetailVO[] bvos = (BudgetAdjustDetailVO[])aggvo.getChildren(BudgetAdjustDetailVO.class);
                    if (null != bvos) {
                        for (BudgetAdjustDetailVO bvo : bvos) {
                            Object amount_adjust = bvo.getAttributeValue("amount_adjust");// 项目调整金额
                            Object amount_after_adjust = bvo.getAttributeValue("amount_after_adjust");// 项目调整后的金额
                            Object pk_project = bvo.getAttributeValue("pk_project");// 项目批复 项目
                            HashMap<String, Object> map = new HashMap<>();
                            map.put("tzmonery",amount_adjust);
                            map.put("zzmonery",amount_after_adjust);
                            pfs.put(pk_project.toString(), map);
                        }
                    }
                }

            }
            if ( !liskfbzs.isEmpty()  && liskfbzs.size() > 0 ) {
                // 获取所有的预算编制单据
                AggBudgetMakeVO[] aggbudVOs = util.getBudgetMakeVOService().listAggBudgetMakeVOByPk(liskfbzs.toArray(String[]::new));
                for (AggBudgetMakeVO budgetMakeVO : aggbudVOs) {
                    BudgetMakeVO hvo = budgetMakeVO.getParentVO();
                    String nyear = hvo.getNyear();
                    // 预算编制明细
                    BudgetMakeDetailVO[] bzvos = (BudgetMakeDetailVO[])budgetMakeVO.getChildren(BudgetMakeDetailVO.class);
                    List<String> lists = new ArrayList<>();
                    Map<String, HashMap<String,Object>> maps = new HashMap<>();
                    if(!ArrayUtils.isEmpty(bzvos)){
                        for (BudgetMakeDetailVO bzvo : bzvos) {
                            Object pk_project = bzvo.getAttributeValue("pk_project"); // 对应预算申请单
                            if(null !=  pk_project){
                                if(!lists.contains(pk_project.toString())){
                                    lists.add(pk_project.toString());
                                }
                                AggPjapplVO[] sqdaggvos = util.querySQD.query(new String[]{pk_project.toString()});
                                if(ArrayUtils.isEmpty(sqdaggvos)){
                                    continue;
                                }
                                PjapplPVO[] cgvos = (PjapplPVO[])sqdaggvos[0].getChildren(PjapplPVO.class);
                                if(ArrayUtils.isEmpty(cgvos)){
                                    continue;
                                }
                                for (PjapplPVO cgvo : cgvos ){
                                    Object vbdef1 = cgvo.getAttributeValue("vbdef1");
                                    if(null != vbdef1){
                                        HashMap<String, Object> item = new HashMap<>();
                                        bzvo.getAttributeValue("pk_project");
                                        Map<String,Object> tzmap = pfs.get(pk_project);
                                        item.put("threeprotzmoney",tzmap.get("tzmonery"));
                                        item.put("kymoney",tzmap.get("zzmonery"));
                                        item.put("threeprofinysmoney",tzmap.get("zzmonery"));
                                        item.put("threeproysmoney",tzmap.get("zzmonery"));
                                        item.put("budstate", 1);
                                        item.put("status", VOStatus.UPDATED);
                                        item.put("modifyobj", "HOP");
                                        maps.put(nyear+"_spli_"+vbdef1, item);
                                    }

                                }
                            }
                        }
                    }
                    if(maps.isEmpty()) return;
                    util.handAggAggSjxmVO(maps);

                }

            }
        }
    }


    /**
     * 预算调整收回回写采购系统四级项目
     * @param aggvos
     * @throws BusinessException
     */
    public static void callbackUNSAVEAggBudgetAdjustVO(AggBudgetAdjustVO[] aggvos) throws BusinessException{
        CGFourWriteBakDataUtil util = new CGFourWriteBakDataUtil();
        if (aggvos == null || aggvos.length == 0) {
        }else {
            ArrayList<String> pks = new ArrayList<>();
            for (AggBudgetAdjustVO aggvo : aggvos) {
                String pk = aggvo.getParentVO().getPk_budgetadjust();
                pks.add(pk);
            }
            aggvos = util.queryTZ.query(pks.toArray(new String[0]));
            // 获取所有的对应预算编制
            HashMap<String, Map<String, Object>> pfs = new HashMap<>();// 批复数 二下
            List<String> liskfbzs = new ArrayList<>(); // 所有所提交预算批复中所有的项目
            for (AggBudgetAdjustVO aggvo : aggvos) {
                BudgetAdjustVO hvo = aggvo.getParentVO();
                Object pk_budgetmake = hvo.getAttributeValue("pk_budgetmake");
                if(null !=  pk_budgetmake){
                    liskfbzs.add(pk_budgetmake.toString());
                }
                BudgetAdjustDetailVO[] bvos = (BudgetAdjustDetailVO[])aggvo.getChildren(BudgetAdjustDetailVO.class);
                if (null != bvos) {
                    for (BudgetAdjustDetailVO bvo : bvos) {
                        Object amount_adjust = bvo.getAttributeValue("amount_adjust");// 项目调整金额
                        Object amount_after_adjust = bvo.getAttributeValue("amount_after_adjust");// 项目调整后的金额
                        Object pk_project = bvo.getAttributeValue("pk_project");// 项目批复 项目
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("tzmonery",amount_adjust);
                        map.put("zzmonery",amount_after_adjust);
                        pfs.put(pk_project.toString(), map);
                    }
                }

            }
            if ( !liskfbzs.isEmpty()  && liskfbzs.size() > 0 ) {
                // 获取所有的预算编制单据
                AggBudgetMakeVO[] aggbudVOs = util.getBudgetMakeVOService().listAggBudgetMakeVOByPk(liskfbzs.toArray(String[]::new));
                for (AggBudgetMakeVO budgetMakeVO : aggbudVOs) {
                    BudgetMakeVO hvo = budgetMakeVO.getParentVO();
                    String nyear = hvo.getNyear();
                    // 预算编制明细
                    BudgetMakeDetailVO[] bzvos = (BudgetMakeDetailVO[])budgetMakeVO.getChildren(BudgetMakeDetailVO.class);
                    List<String> lists = new ArrayList<>();
                    Map<String, HashMap<String,Object>> maps = new HashMap<>();
                    if(!ArrayUtils.isEmpty(bzvos)){
                        for (BudgetMakeDetailVO bzvo : bzvos) {
                            Object amount_seconddown = bzvo.getAttributeValue("amount_seconddown");
                            Object pk_project = bzvo.getAttributeValue("pk_project"); // 对应预算申请单
                            if(null !=  pk_project){
                                lists.add(pk_project.toString());
                                AggPjapplVO[] sqdaggvos = util.querySQD.query(new String[]{pk_project.toString()});
                                if(ArrayUtils.isEmpty(sqdaggvos)){
                                    continue;
                                }
                                PjapplPVO[] cgvos = (PjapplPVO[])sqdaggvos[0].getChildren(PjapplPVO.class);
                                if(ArrayUtils.isEmpty(cgvos)){
                                    continue;
                                }
                                for (PjapplPVO cgvo : cgvos ){
                                    Object vbdef1 = cgvo.getAttributeValue("vbdef1");
                                    if(null != vbdef1){
                                        HashMap<String, Object> item = new HashMap<>();
                                        if(pfs.containsKey(pk_project)){
                                            Map<String, Object> map = pfs.get(pk_project);
                                            // 因为是收回所以取消去掉当前单据正向提交的调整金额
                                            UFDouble tz = map.get("tzmonery") == null ? new UFDouble(0) : new UFDouble(map.get("tzmonery").toString()).multiply(new UFDouble(-1));
                                            item.put("threeprotzmoney", tz);

                                        }
                                        item.put("bzmonery",  amount_seconddown);
                                        item.put("kymoney",amount_seconddown);
                                        item.put("threeprofinysmoney",amount_seconddown);
                                        item.put("threeproysmoney",amount_seconddown);
                                        item.put("budstate", 1);
                                        item.put("status", VOStatus.UPDATED);
                                        item.put("modifyobj", "HOP");
                                        maps.put(nyear+"_spli_"+vbdef1, item);
                                    }

                                }
                            }
                        }
                    }
                    if(maps.isEmpty()) return;
                    util.handAggAggSjxmVO(maps);

                }

            }
        }
    }

    /**
     * 预算批复提交回写采购系统四级项目
     * @param aggvos
     * @throws BusinessException
     */
    public static void callbackAPPROVEAggBudgetReplyVO(AggBudgetReplyVO[] aggvos) throws BusinessException{
        if(ArrayUtils.isEmpty(aggvos)){
           return ;
        }
        for(AggBudgetReplyVO aggvo : aggvos){
            BudgetReplyVO hvo = aggvo.getParentVO();
            Integer taskstage = hvo.getTaskstage(); // 任务阶段 2:一下 4: 二下批复  一上=1,一下=2,二上=3,二下=4
            // 一上编制=1,一上审批=2,一上上报=3,一下处理=4,一下审批=5,一下批复=6,二上编制=7,二上处理=8,二上审批=9,二上上报=10,二下处理=11,二下审批=12,二下批复=13,编报完成=99
            Integer taskstate = hvo.getTaskstate(); // 任务状态 6:一下批复 13:二下处理 11:二下处理 9:二上审批
            if(!(Integer.valueOf(4).equals(taskstage) && Integer.valueOf(13).equals(taskstate))) {
                return ;
            }
        }
        CGFourWriteBakDataUtil util = new CGFourWriteBakDataUtil();
        if (aggvos == null || aggvos.length == 0) {
        }else {
            ArrayList<String> pks = new ArrayList<>();
            for (AggBudgetReplyVO aggvo : aggvos) {
                String pk = aggvo.getParentVO().getPk_budgetreply();
                pks.add(pk);
            }
            aggvos = util.queryPF.query(pks.toArray(new String[0]));
            // 获取所有的对应预算编制
            List<String> liskfbzs = new ArrayList<>(); // 所有所提交预算批复中所有的项目
            HashMap<String, Object> pfs = new HashMap<>();// 批复数 二下
            for (AggBudgetReplyVO aggvo : aggvos) {
                BudgetReplyVO hvo = aggvo.getParentVO();
                Object pk_secondupbill = hvo.getAttributeValue("pk_secondupbill");
                if(null !=  pk_secondupbill){
                    liskfbzs.add(pk_secondupbill.toString());
                    BudgetReplyDetailVO[] bvos = (BudgetReplyDetailVO[])aggvo.getChildren(BudgetReplyDetailVO.class);
                    if (null != bvos) {
                        for (BudgetReplyDetailVO bvo : bvos) {
                            Object amount_seconddown = bvo.getAttributeValue("amount_seconddown");// 项目批复 二下批复数
                            Object pk_project = bvo.getAttributeValue("pk_project");// 项目批复 项目
                            if(pfs.isEmpty()){
                                pfs.put(pk_project.toString(), amount_seconddown);
                            }else{
                                if (pfs.containsKey(pk_project.toString())){
                                    UFDouble yDouble = new UFDouble(pfs.get(pk_project.toString()).toString());
                                    UFDouble add = yDouble.add(new UFDouble(amount_seconddown.toString()));
                                    pfs.put(pk_project.toString(), add);
                                }else{
                                    pfs.put(pk_project.toString(), amount_seconddown);
                                }


                            }


                        }
                    }
                }

            }
            if ( !liskfbzs.isEmpty()  && liskfbzs.size() > 0 ) {
                // 获取所有的预算编制单据
                AggBudgetMakeVO[] aggbudVOs = util.getBudgetMakeVOService().listAggBudgetMakeVOByPk(liskfbzs.toArray(String[]::new));
                for (AggBudgetMakeVO budgetMakeVO : aggbudVOs) {
                    BudgetMakeVO hvo = budgetMakeVO.getParentVO();
                    String nyear = hvo.getNyear();
                    // 预算编制明细
                    BudgetMakeDetailVO[] bzvos = (BudgetMakeDetailVO[])budgetMakeVO.getChildren(BudgetMakeDetailVO.class);
                    List<String> lists = new ArrayList<>();
                    Map<String, HashMap<String,Object>> maps = new HashMap<>();
                    if(!ArrayUtils.isEmpty(bzvos)){
                        for (BudgetMakeDetailVO bzvo : bzvos) {
                            Object pk_project = bzvo.getAttributeValue("pk_project"); // 对应预算申请单
                            if(null !=  pk_project){
                                lists.add(pk_project.toString());
                                // Object amount_adjust = bzvo.getAttributeValue("amount_adjust");  // 调整金额
                                Object amount = bzvo.getAttributeValue("amount"); // 最终预算金额 此时还没回写数据为空
                                AggPjapplVO[] sqdaggvos = util.querySQD.query(new String[]{pk_project.toString()});
                                if (ArrayUtils.isEmpty(sqdaggvos)){
                                    continue;
                                }
                                PjapplPVO[] cgvos = (PjapplPVO[])sqdaggvos[0].getChildren(PjapplPVO.class);
                                if(ArrayUtils.isEmpty(cgvos)){
                                    continue;
                                }
                                for (PjapplPVO cgvo : cgvos ){
                                    Object vbdef1 = cgvo.getAttributeValue("vbdef1");
                                    if(null != vbdef1){
                                        HashMap<String, Object> item = new HashMap<>();
                                        bzvo.getAttributeValue("pk_project");
                                        Object pfmonery = pfs.get(pk_project);
                                        HashMap<String, Object> pmap = util.getParentProjectAlls(pk_project);
                                        item.put("oneprono" ,pmap.get("oneprono"));
                                        item.put("oneproname" ,pmap.get("oneproname"));
                                        item.put("twoprono" ,pmap.get("twoprono"));
                                        item.put("twoproname" ,pmap.get("twoproname"));
                                        item.put("threeprono" ,pmap.get("threeprono"));
                                        item.put("threeproname" ,pmap.get("threeproname"));
                                        item.put("bzmonery",pfmonery);
                                        item.put("kymoney",pfmonery);
                                        item.put("threeprofinysmoney",pfmonery);
                                        item.put("threeproysmoney",pfmonery);
                                        item.put("threeprotzmoney", new UFDouble(0));
                                        item.put("budstate", 1);
                                        item.put("status", VOStatus.UPDATED);
                                        item.put("modifyobj", "HOP");
                                        maps.put(nyear+"_spli_"+vbdef1.toString(), item);
                                    }

                                }
                            }
                        }
                    }
                    if(maps.isEmpty()) return;
                    util.handAggAggSjxmVO(maps);
                }

            }
        }
    }

    /**
     * 处理四级项目
     * @param maps
     * @throws BusinessException
     */
    protected void handAggAggSjxmVO(Map<String, HashMap<String,Object>> maps) throws BusinessException{
        CGFourWriteBakDataUtil util = new CGFourWriteBakDataUtil();
        List<AggSjxmVO> listaggvos = new ArrayList<>();
        for(String key : maps.keySet()){
            String[] spliS = key.split("_spli_");
            String year = spliS[0];
            String pk = spliS[1];
            AggSjxmVO[] aggvos = util.queryCG.query(new String[]{pk});
            if(ArrayUtil.isEmpty(aggvos)) return;
            SjxmHVO hvo = aggvos[0].getParentVO();
            hvo.setStatus(VOStatus.UPDATED);
            SjxmBVO[] bvos = (SjxmBVO[])aggvos[0].getChildrenVO();
            if(!ArrayUtils.isEmpty(bvos)){
                for (SjxmBVO bvo : bvos) {
                    if(year.equals(bvo.getYsyear())){
                        bvo.setStatus(VOStatus.UPDATED);
                        HashMap<String, Object> map = maps.get(key); // 需要处理的字段
                        Set<String> attt = map.keySet();
                        for (String att : attt) {
                            if("status".equals(att)){
                                bvo.setStatus(Integer.parseInt(map.get(att).toString()));
                            }else if("threeprotzmoney".equals(att)){
                                UFDouble billje =  map.get(att) == null ? new UFDouble(0) : new UFDouble(map.get(att).toString());
                                UFDouble tz =  bvo.getThreeprotzmoney() == null ? new UFDouble(0) : bvo.getThreeprotzmoney();
                                UFDouble zztz = tz.add(billje);
                                bvo.setAttributeValue("threeprotzmoney", zztz);
                            }else{
                                bvo.setAttributeValue(att, map.get(att));

                            }
                        }
                    }
                }
                listaggvos.add(aggvos[0]);
            }
        }
        if(!listaggvos.isEmpty()) {
            util.getSjxmHVOService().saveAggSjxmVO(listaggvos.toArray(new AggSjxmVO[0]));
        }
    }

    /**
     * 预算批复收回回写采购系统四级项目
     * @param aggvos
     * @throws BusinessException
     */
    public static void callbackUNSAVEAggBudgetReplyVO(AggBudgetReplyVO[] aggvos) throws BusinessException{
        if(ArrayUtils.isEmpty(aggvos)){
            return ;
        }
        for(AggBudgetReplyVO aggvo : aggvos){
            BudgetReplyVO hvo = aggvo.getParentVO();
            Integer taskstage = hvo.getTaskstage(); // 任务阶段 2:一下 4: 下批复
            Integer taskstate = hvo.getTaskstate(); // 任务状态 6:一下批复 13:二下处理 11
            if(!(Integer.valueOf(4).equals(taskstage) && Integer.valueOf(11).equals(taskstate))) {
                return ;
            }
        }
        CGFourWriteBakDataUtil util = new CGFourWriteBakDataUtil();// 11 二下批复 Taskstate
        if (aggvos == null || aggvos.length == 0) {
        }else {
            ArrayList<String> pks = new ArrayList<>();
            for (AggBudgetReplyVO aggvo : aggvos) {
                String pk = aggvo.getParentVO().getPk_budgetreply();
                pks.add(pk);
            }
            aggvos = util.queryPF.query(pks.toArray(new String[0]));
            // 获取所有的对应预算编制
            List<String> liskfbzs = new ArrayList<>(); // 所有所提交预算批复中所有的项目
            for (AggBudgetReplyVO aggvo : aggvos) {
                BudgetReplyVO hvo = aggvo.getParentVO();
                Object pk_secondupbill = hvo.getAttributeValue("pk_secondupbill");
                if(null !=  pk_secondupbill){
                    liskfbzs.add(pk_secondupbill.toString());
                }

            }
            if ( !liskfbzs.isEmpty()  && liskfbzs.size() > 0 ) {
                // 获取所有的预算编制单据
                AggBudgetMakeVO[] aggbudVOs = util.getBudgetMakeVOService().listAggBudgetMakeVOByPk(liskfbzs.toArray(String[]::new));
                for (AggBudgetMakeVO budgetMakeVO : aggbudVOs) {
                    BudgetMakeVO hvo = budgetMakeVO.getParentVO();
                    String nyear = hvo.getNyear();
                    // 预算编制明细
                    BudgetMakeDetailVO[] bzvos = (BudgetMakeDetailVO[])budgetMakeVO.getChildren(BudgetMakeDetailVO.class);
                    List<String> lists = new ArrayList<>();
                    Map<String, HashMap<String,Object>> maps = new HashMap<>();
                    if(!ArrayUtils.isEmpty(bzvos)){
                        for (BudgetMakeDetailVO bzvo : bzvos) {
                            Object pk_project = bzvo.getAttributeValue("pk_project"); // 对应预算申请单
                            if(null !=  pk_project){
                                lists.add(pk_project.toString());
                                AggPjapplVO[] sqdaggvos = util.querySQD.query(new String[]{pk_project.toString()});
                                if(ArrayUtils.isEmpty(sqdaggvos)){
                                    continue;
                                }
                                PjapplPVO[] cgvos = (PjapplPVO[])sqdaggvos[0].getChildren(PjapplPVO.class);
                                if(ArrayUtils.isEmpty(cgvos)){
                                   continue;
                                }
                                for (PjapplPVO cgvo : cgvos ){
                                    Object vbdef1 = cgvo.getAttributeValue("vbdef1");
                                    if(null != vbdef1){
                                        HashMap<String, Object> item = new HashMap<>();
//                                        item.put("budstate", 3); 二上预算批复收回不调整预算状态
                                        item.put("modifyobj", "HOP");
                                        item.put("kymoney", new UFDouble(0)); // 可用金额
                                        item.put("threeprofinysmoney", new UFDouble(0)); // 三级项目最终预算金额
                                        item.put("threeproysmoney", new UFDouble(0)); // 三级项目预算金额
                                        item.put("status", VOStatus.UPDATED);
//                                        item.put("threeprotzmoney", ); // 调整金额
                                        maps.put(nyear+"_spli_"+vbdef1.toString(), item);
                                    }

                                }
                            }
                        }
                    }
                    if(maps.isEmpty()) return;
                    util.handAggAggSjxmVO(maps);
                }

            }
        }
    }

    /**
     * 获取当前项目上级项目
     * @param belongpro
     * @return
     * @throws BusinessException
     */
    protected HashMap<String, Object> getParentProjectAlls(Object belongpro) throws  BusinessException{
        HashMap<String, Object> param = new HashMap<String,Object>();
        String sql = "select def1 from bd_project where dr = 0 " +
                " and pk_project ='" + belongpro + "' ";
        Object obj = this.getBaseDAO().executeQuery(sql, new ColumnProcessor());
        if(obj == null ) return param;
        Integer i = Integer.valueOf(obj.toString());
        Object pk_project = belongpro;
        while(i > 0 ) {
            String isql = "select project_code,project_name,pk_parentpro from bd_project where dr = 0 " +
                    " and pk_project ='" + pk_project + "' ";
            Object iobj = this.getBaseDAO().executeQuery(isql, new MapProcessor());
            if(iobj ==  null) {
                i--;
                continue;
            }
            Map<String,Object> map  =  (Map<String,Object>)iobj;
            Object project_code = map.get("project_code");
            Object project_name = map.get("project_name");
            pk_project = map.get("pk_parentpro");
            if(i == 3) {
                param.put("threeprono", project_code);
                param.put("threeproname", project_name);

            }else if(i == 2) {
                param.put("twoprono", project_code);
                param.put("twoproname", project_name);

            }else if(i == 1) {
                param.put("oneprono", project_code);
                param.put("oneproname", project_name);
            }
            i--;
        }
        return  param;
    }

    /**
     * 回写采购系统四级项目处理
     * @param aggcgVOs 采购系统
     * @param maps
     * @return
     * @throws BusinessException
     */
    protected  AggFourcgxmVO[] setCallbackUNSAVEAggBudgetReplyVO(AggFourcgxmVO[] aggcgVOs ,Map<String, HashMap<String,Object>> maps) throws BusinessException{
        for (AggFourcgxmVO aggcgVO : aggcgVOs) {
            FourcgxmVO hvo = aggcgVO.getParentVO();
            String key = hvo.getPrimaryKey();
            if(maps.containsKey(key)){
                HashMap<String, Object> map = maps.get(key);
                hvo.setAttributeValue("kymoney", new UFDouble(0)); // 可用金额
                hvo.setAttributeValue("threeprofinysmoney", new UFDouble(0)); // 三级项目最终预算金额
                hvo.setAttributeValue("threeproysmoney", new UFDouble(0)); // 三级项目预算金额
                hvo.setAttributeValue("threeprotzmoney",new UFDouble(0)); // 调整金额
                hvo.setAttributeValue("fourstate","2"); // 四级项目状态 项目已打包
                hvo.setAttributeValue("oneprono",null);
                hvo.setAttributeValue("oneproname",null);
                hvo.setAttributeValue("twoprono",null);
                hvo.setAttributeValue("twoproname",null);
                hvo.setAttributeValue("threeprono",null);
                hvo.setAttributeValue("threeproname",null);
                hvo.setAttributeValue("budstate",2);  // 预算状态
                hvo.setStatus(1);
            }
        }
        return aggcgVOs;
    }

    /**
     * 回写采购系统四级项目处理
     * @param aggcgVOs 采购系统
     * @param maps
     * @return
     * @throws BusinessException
     */
    protected  AggFourcgxmVO[] setCallbackUNSAVEAggBudgetAdjustVO(AggFourcgxmVO[] aggcgVOs ,Map<String, HashMap<String,Object>> maps) throws BusinessException{
        for (AggFourcgxmVO aggcgVO : aggcgVOs) {
            FourcgxmVO hvo = aggcgVO.getParentVO();
            String key = hvo.getPrimaryKey();
            if(maps.containsKey(key)){
                HashMap<String, Object> map = maps.get(key);
                Object bzmonery = map.get("bzmonery");
                hvo.setAttributeValue("kymoney", bzmonery); // 可用金额
                hvo.setAttributeValue("threeprofinysmoney", bzmonery); // 三级项目最终预算金额
                hvo.setAttributeValue("threeproysmoney", bzmonery); // 三级项目预算金额
                hvo.setAttributeValue("threeprotzmoney",new UFDouble(0)); // 调整金额
                hvo.setAttributeValue("fourstate","2"); // 四级项目状态 项目已打包
                hvo.setAttributeValue("budstate",2);  // 预算状态
                hvo.setStatus(1);
            }
        }
        return aggcgVOs;
    }

    /**
     * 预算调整回写采购系统四级项目处理
     * @param aggcgVOs 采购系统
     * @param maps
     * @return
     * @throws BusinessException
     */
    protected  AggFourcgxmVO[] setCallbackSAVEAggBudgetAdjustVO(AggFourcgxmVO[] aggcgVOs ,Map<String, HashMap<String,Object>> maps) throws BusinessException{
        for (AggFourcgxmVO aggcgVO : aggcgVOs) {
            FourcgxmVO hvo = aggcgVO.getParentVO();
            String key = hvo.getPrimaryKey();
            if(maps.containsKey(key)){
                HashMap<String, Object> map = maps.get(key);
                hvo.setAttributeValue("kymoney",map.get("zzmonery")); // 可用金额
                hvo.setAttributeValue("threeprofinysmoney",map.get("zzmonery")); // 三级项目最终预算金额
                hvo.setAttributeValue("threeproysmoney",map.get("zzmonery")); // 三级项目预算金额
                hvo.setAttributeValue("threeprotzmoney", map.get("tzmonery")); // 调整金额
                hvo.setAttributeValue("fourstate","2"); // 四级项目状态 项目已打包
                hvo.setAttributeValue("budstate",1);  // 预算状态
                hvo.setStatus(1);
            }
        }
        return aggcgVOs;

    }
    /**
     * 预算编制审回写采购系统四级项目处理
     * @param aggcgVOs 采购系统
     * @param maps
     * @return
     * @throws BusinessException
     */
    protected  AggFourcgxmVO[] setCallbackSAVEAggBudgetReplyVO(AggFourcgxmVO[] aggcgVOs ,Map<String, HashMap<String,Object>> maps) throws BusinessException{
        for (AggFourcgxmVO aggcgVO : aggcgVOs) {
            FourcgxmVO hvo = aggcgVO.getParentVO();
            String key = hvo.getPrimaryKey();
            if(maps.containsKey(key)){
                HashMap<String, Object> map = maps.get(key);
                hvo.setAttributeValue("kymoney",map.get("bzmonery")); // 可用金额
                hvo.setAttributeValue("threeprofinysmoney",map.get("bzmonery")); // 三级项目最终预算金额
                hvo.setAttributeValue("threeproysmoney",map.get("bzmonery")); // 三级项目预算金额
                hvo.setAttributeValue("threeprotzmoney", new UFDouble(0)); // 调整金额
                hvo.setAttributeValue("oneprono",map.get("oneprono"));
                hvo.setAttributeValue("oneproname",map.get("oneproname"));
                hvo.setAttributeValue("twoprono",map.get("twoprono"));
                hvo.setAttributeValue("twoproname",map.get("twoproname"));
                hvo.setAttributeValue("threeprono",map.get("threeprono"));
                hvo.setAttributeValue("threeproname",map.get("threeproname"));
                hvo.setAttributeValue("fourstate","2"); // 四级项目状态 项目已打包
                hvo.setAttributeValue("budstate",1);  // 预算状态
                hvo.setStatus(1);
            }
        }
        return aggcgVOs;

    }

    public IUAPQueryBS getQueryBS() {
        if(null == this.queryBS){
            this.queryBS = NCLocator.getInstance().lookup(IUAPQueryBS.class);
        }
        return this.queryBS;
    }

    public BaseDAO getBaseDAO() {
        if (null == this.baseDAO){
            this.baseDAO = new BaseDAO();
        }
        return this.baseDAO;
    }

    public ISjxmHVOService getSjxmHVOService() {
        if(null == this.sjxmHVOService){
            this.sjxmHVOService = NCLocator.getInstance().lookup(ISjxmHVOService.class);
        }
        return this.sjxmHVOService;
    }

    public IPJApplHVOService getPjApplHVOService() {
        if(null == this.pjApplHVOService){
            this.pjApplHVOService = NCLocator.getInstance().lookup(IPJApplHVOService.class);
        }
        return this.pjApplHVOService;
    }

    public IBudgetMakeVOService getBudgetMakeVOService() {
        if (null == this.budgetMakeVOService){
            this.budgetMakeVOService = NCLocator.getInstance().lookup(IBudgetMakeVOService.class);
        }
        return this.budgetMakeVOService;
    }
}
